/*
 * Copyright (c) 1996, David Mazieres <dm@uun.org>
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 * Arc4 random number generator for OpenBSD.
 *
 * This code is derived from section 17.1 of Applied Cryptography,
 * second edition, which describes a stream cipher allegedly
 * compatible with RSA Labs "RC4" cipher (the actual description of
 * which is a trade secret).  The same algorithm is used as a stream
 * cipher called "arcfour" in Tatu Ylonen's ssh package.
 *
 * Here the stream cipher has been modified always to include entropy
 * when initializing the state.  That makes it impossible to
 * regenerate the same random sequence twice, so this can't be used
 * for encryption, but will generate good random numbers.
 *
 * RC4 is a registered trademark of RSA Laboratories.
 */

/* Modified by Robert Connolly for Glibc. April 23, 2007 */

/*
 * Modified by Vadim Zhukov. May 06, 2010:
 *
 * Patches taken from upstream (arc4random_buf() and arc4random_uniform())
 */

#include <sys/types.h>
#include <sys/time.h>

#if defined(HAVE_RANDOM_ERANDOM)
#include <sys/sysctl.h>
#endif

#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

#include "../config.h"

#ifdef __GNUC__
#define inline __inline
#else
#define inline
#endif

struct arc4_stream {
	u_int8_t i;
	u_int8_t j;
	u_int8_t s[256];
};

static int rs_initialized;
static struct arc4_stream rs;
static pid_t arc4_stir_pid;
static int arc4_count;

static inline u_int8_t arc4_getbyte(struct arc4_stream *);

#if defined(TEST)
u_int32_t arc4random(void);
void arc4random_stir(void);
void arc4random_addrandom(unsigned char *, int);
#endif

#if !defined(_LIBC)
#define __getpid getpid
#define __gettimeofday gettimeofday
#define __open open
#define __read read
#define __close close
#endif

static inline void
arc4_init(struct arc4_stream *as)
{
	int     n;

	for (n = 0; n < 256; n++)
		as->s[n] = n;
	as->i = 0;
	as->j = 0;
}

static inline void
arc4_addrandom(struct arc4_stream *as, u_char *dat, int datlen)
{
	int     n;
	u_int8_t si;

	as->i--;
	for (n = 0; n < 256; n++) {
		as->i = (as->i + 1);
		si = as->s[as->i];
		as->j = (as->j + si + dat[n % datlen]);
		as->s[as->i] = as->s[as->j];
		as->s[as->j] = si;
	}
	as->j = as->i;
}

static void
arc4_stir(struct arc4_stream *as)
{
	int	n, fd;
	u_char	rnd[128];
	struct timeval tv;

#if defined(HAVE_RANDOM_ERANDOM)
	/* This is the most efficient method (1 syscall). */
	int     mib[3];
	size_t  len;

	mib[0] = CTL_KERN;
	mib[1] = KERN_RANDOM;
	mib[2] = RANDOM_ERANDOM;

	len = sizeof(rnd);
	if (__sysctl(mib, 3, rnd, &len, NULL, 0) == -1)
	/* Sysctl failed? Try /dev/urandom (3 syscalls). */
#endif
	  fd = __open(PRNG_DEV, O_RDONLY, 0);
	  if (fd != -1) {
		__read(fd, rnd, sizeof(rnd));
		__close(fd);
	  }
	  /* Did the pseudo-random device fail? Use gettimeofday(). */
	  else if (__gettimeofday(&tv, NULL) != (-1)) {

		/* Initialize the first element so it's hopefully not '0',
		 * to help out the next loop. Tossing in some prime numbers
		 * probably can't hurt. */
		rnd[0] = (tv.tv_sec % 10000) * 3 + tv.tv_usec * 7 + \
			(__getpid() % 1000) * 13;

		for (n = 1; n < 127 ; n++) {

		/* Take advantage of the stack space. Only initialize
		 * elements equal to '0'. This will make the rnd[]
		 * array much less vulnerable to timing attacks. Here
		 * we'll stir getpid() into the value of the previous
		 * elememnt. Approximately 1 in 128 elements will still
		 * become '0', so it will be a nightmare to try to
		 * predict this array. */

			if (rnd[n] == 0) {
				rnd[n] = ((rnd[n - 1] + n) ^ \
					((__getpid() % 1000) * 17));
			}
		}
	  }
	  else {
	  /* gettimeofday() failed? Do the same thing as above, but only
	   * with getpid(). This is very bad, but arc4random() should never
	   * fail, so never give up. */

		rnd[0] = (__getpid() % 1000) * 19;
		for (n = 1; n < 127 ; n++) {
			if (rnd[n] == 0) {
				rnd[n] = ((rnd[n - 1] + n) ^ \
					((__getpid() % 1000) * 23));
			}
		}
	  }
	  /* else??? Print warning here. */

	arc4_stir_pid = __getpid();
	arc4_addrandom(as, rnd, sizeof(rnd));

	/*
	 * Discard early keystream, as per recommendations in:
	 * http://www.wisdom.weizmann.ac.il/~itsik/RC4/Papers/Rc4_ksa.ps
	 */
	for (n = 0; n < 256; n++)
		(void)arc4_getbyte(as);
	arc4_count = 1600000;
}

static inline void
arc4_stir_if_needed(void)
{
	pid_t pid = getpid();

	if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != pid)
	{
		arc4_stir_pid = pid;
		arc4_stir(&rs);
	}
}

static inline u_int8_t
arc4_getbyte(struct arc4_stream *as)
{
	u_int8_t si, sj;

	as->i = (as->i + 1);
	si = as->s[as->i];
	as->j = (as->j + si);
	sj = as->s[as->j];
	as->s[as->i] = sj;
	as->s[as->j] = si;
	return (as->s[(si + sj) & 0xff]);
}

/*
 * __arc4_getbyte() is a libc private function intended for use
 * with malloc(3) without calling getpid(2). It's good for
 * fetching a specific amount of bytes.
 */
u_int8_t
__arc4_getbyte(void)
{
	if (--arc4_count == 0 || !rs_initialized)
		arc4random_stir();
	return arc4_getbyte(&rs);
}

static inline u_int32_t
arc4_getword(struct arc4_stream *as)
{
	u_int32_t val;
	val = arc4_getbyte(as) << 24;
	val |= arc4_getbyte(as) << 16;
	val |= arc4_getbyte(as) << 8;
	val |= arc4_getbyte(as);
	return val;
}

void
arc4random_stir(void)
{
	if (!rs_initialized) {
		arc4_init(&rs);
		rs_initialized = 1;
	}
	arc4_stir(&rs);
}

void
arc4random_addrandom(u_char *dat, int datlen)
{
	if (!rs_initialized)
		arc4random_stir();
	arc4_addrandom(&rs, dat, datlen);
}

u_int32_t
arc4random(void)
{
	arc4_count -= 4;
	if (arc4_count <= 0 || !rs_initialized || arc4_stir_pid != __getpid())
		arc4random_stir();
	return arc4_getword(&rs);
}

void
arc4random_buf(void *_buf, size_t n)
{
	u_char *buf = (u_char *)_buf;
	arc4_stir_if_needed();
	while (n--) {
		if (--arc4_count <= 0)
			arc4_stir(&rs);
		buf[n] = arc4_getbyte(&rs);
	}
}

/*
 * Calculate a uniformly distributed random number less than upper_bound
 * avoiding "modulo bias".
 *
 * Uniformity is achieved by generating new random numbers until the one
 * returned is outside the range [0, 2**32 % upper_bound).  This
 * guarantees the selected random number will be inside
 * [2**32 % upper_bound, 2**32) which maps back to [0, upper_bound)
 * after reduction modulo upper_bound.
 */
u_int32_t
arc4random_uniform(u_int32_t upper_bound)
{
	u_int32_t r, min;

	if (upper_bound < 2)
		return 0;

#if (ULONG_MAX > 0xffffffffUL)
	min = 0x100000000UL % upper_bound;
#else
	/* Calculate (2**32 % upper_bound) avoiding 64-bit math */
	if (upper_bound > 0x80000000)
		min = 1 + ~upper_bound;		/* 2**32 - upper_bound */
	else {
		/* (2**32 - (x * 2)) % x == 2**32 % x when x <= 2**31 */
		min = ((0xffffffff - (upper_bound * 2)) + 1) % upper_bound;
	}
#endif

	/*
	 * This could theoretically loop forever but each retry has
	 * p > 0.5 (worst case, usually far better) of selecting a
	 * number inside the range we need, so it should rarely need
	 * to re-roll.
	 */
	for (;;) {
		r = arc4random();
		if (r >= min)
			break;
	}

	return r % upper_bound;
}

#if defined(TEST)
#include <stdio.h>
int main(void)
{
	int random_number;
	random_number = arc4random() % 65536;
	printf("%d\n", random_number);
	return 0;
}
#endif
